package com.example.distributelock.controller;

import com.example.distributelock.dao.DistributeLockMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试分布式锁,javaJUC提供的锁并不能用在分布式上边,这就导致了我们需要依赖一个中间件
 *
 * @author caryguan 感谢刘宇波大神点拨!!
 * @version V1.0
 * @Package com.example.distributelock.controller
 * @date 2020/10/8 1:18
 */

@RestController
@Slf4j
public class DemoController {

    @Resource
    private DistributeLockMapper distributeLockMapper;
    private Lock lock = new ReentrantLock();

    @RequestMapping("singleLock")
    //这个transaction默认的回滚异常是runtimeException,如果是手动抛出的异常不会进行回滚,所以我在这声明了异常类型
    //并且,这个事务注解如果不打上的话,数据库会在运行sql后自动提交事务,这样的话,我们的for update数据库的分布式锁就没有起到任何作用了,锁会在提交事务后失效
    @Transactional(rollbackFor = Exception.class)
    public String singleLock() throws Exception {
        log.info("我进入了方法");
        // lock.lock();
        distributeLockMapper.selectDistributeLock("demo");
        if (distributeLockMapper == null) throw new Exception("分布式锁找不到");
        log.info("我进入了锁");

        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally{
            lock.unlock();
        }
        return "我已经执行完成";
    }
}